﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using GRTVPluginConsole.Entity;

namespace GRTVPluginConsole.Listener.Processors
{
    class PluginDriverRankingProcessor
    {
        //Form1 callback;
        GRTVPluginConsole.Listener.PluginListenerThread.DriverRankReceived callback;
        private byte[] data;
        public PluginDriverRankingProcessor(IPEndPoint ep, byte[] data, GRTVPluginConsole.Listener.PluginListenerThread.DriverRankReceived callback)
        {
            this.data = data;
            this.callback = callback;
        }

        public void ThreadLoop(Object threadContext)
        {
            if (callback != null)
            {
                DriverRank entity = new DriverRank();
                entity.place = data[1];
                entity.slotId = BitConverter.ToInt32(data, 2);
                entity.name = getString(data, 6, 32);
                entity.finishStatus = data[38];
                entity.isInPit = data[39] == 1;
                entity.categoryGroup = getString(data, 40, 32);
                entity.trackDistance = BitConverter.ToDouble(data, 72);
                entity.lapDistance = BitConverter.ToDouble(data, 80);
                entity.team = getString(data, 88, 32);
                entity.number = getString(data, 120, 4);
                entity.carClass = getString(data, 124, 32);
                entity.lastLapTime = BitConverter.ToDouble(data, 156);
                entity.bestLapTime = BitConverter.ToDouble(data, 164);
                entity.s1 = BitConverter.ToDouble(data, 172);
                entity.s2 = BitConverter.ToDouble(data, 180);
                entity.s3 = BitConverter.ToDouble(data, 188);
                entity.maxSpeed = BitConverter.ToDouble(data, 196);
                entity.lastMaxSpeed = BitConverter.ToDouble(data, 204);
                entity.lapsCompleted = BitConverter.ToInt16(data, 212);
                entity.numPitStops = BitConverter.ToInt32(data, 214);
                entity.timeBehindNextInFront = BitConverter.ToDouble(data, 218);
                entity.x = BitConverter.ToDouble(data, 226);
                entity.y = BitConverter.ToDouble(data, 234);
                entity.z = BitConverter.ToDouble(data, 242);
                entity.catImageColor = BitConverter.ToInt32(data, 250);
                entity.catTextColor = BitConverter.ToInt32(data, 254);

                callback(this, entity);
            }
        }
        

        private string getString(byte[] data, int offset, int length)
        {
            for (int i = 0; i < length; i++)
            {
                if (data[offset + i] == 0)
                {
                    return Encoding.ASCII.GetString(data, offset, i);
                }
            }
            return Encoding.ASCII.GetString(data, offset, length);
        }
    }
}
